﻿using System;
using System.Linq;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.DataLayer.Infra;
using ProjetoComperio.Framework.Extensions;

namespace ProjetoComperio.BusinessLogicLayer
{
    public class PublicationBLL : ComperioDataObject
    {
        /// <summary>
        /// This method inserts a new publication
        /// </summary>
        /// <param name="publication"></param>
        public void Create(Publication  publication)
        {
            DbContext.Contributions.Add(publication);
            DbContext.SaveChanges();
        }

        /// <summary>
        /// This method edits a publication
        /// </summary>
        /// <param name="publication"></param>
        public void Edit(Publication publication)
        {
            Publication original = this.RetrievePublication(publication.ContributionID);
            original.CopyValuesFrom(publication);
            DbContext.SaveChanges();

        }

        /// <summary>
        /// This method returns all publications from db
        /// </summary>
        /// <returns></returns>
        public IQueryable<Publication> RetrievePublications()
        {
            return DbContext.Contributions.OfType<Publication>();
        }

        /// <summary>
        /// Retrieves all publications related to the academicPersonID
        /// </summary>
        /// <param name="academicPersonID"></param>
        /// <returns></returns>
        public IQueryable<Publication> RetrievePublications(int academicPersonID)
        {
            return new ContributionBLL().RetrieveAcademicPersonContributions(academicPersonID).OfType<Publication>();
        }

        /// <summary>
        /// This method retrieve a specific publication
        /// </summary>
        /// <param name="publicationId"></param>
        /// <returns></returns>
        public Publication RetrievePublication(Int32 contributionID)
        {
            return DbContext.Contributions.OfType<Publication>().Where(publication => publication.ContributionID == contributionID).FirstOrDefault();
        }

        /// <summary>
        /// This method returns the publications registered on the last week
        /// </summary>
        /// <returns></returns>
        public IQueryable<Publication> RetrieveRecentPublications()
        {
            var dateFromLastWeek = DateTime.Now.AddDays(-7);

            return DbContext.Contributions.OfType<Publication>().Where(publication => publication.RegisterDate >= dateFromLastWeek);
        }
    }
}

